package cn.ticsmyc.tools.reflect;

import org.springframework.lang.Nullable;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

/**
 * @author Ticsmyc
 * @date 2020-12-22 10:29
 */
public class GetTargetObjectFromProxy {

    public static Object getTarget(Object proxy) throws NoSuchFieldException, IllegalAccessException {
        if(isCglibProxy(proxy)){
            return getTargetFromCglibProxy(proxy);
        }else if(isJdkProxy(proxy)){
            return getTargetFromJdkProxy(proxy);
        }else{
            return proxy;
        }
    }

    /**
     * 从jdk动态代理的代理类中获取被代理类
     * @param proxy
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Object getTargetFromJdkProxy(Object proxy) throws NoSuchFieldException, IllegalAccessException {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);

        Object hObj = h.get(proxy);
        Field target = hObj.getClass().getDeclaredField("target");
        target.setAccessible(true);

        Object o = target.get(hObj);
        return o;
    }

    /**
     * 从cglib代理类中获取被代理类
     * @param proxy
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Object getTargetFromCglibProxy(Object proxy) throws NoSuchFieldException, IllegalAccessException {
        Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
        h.setAccessible(true);

        //拿到proxy对象的CGLIB$CALLBACK_0对象
        Object o = h.get(proxy);

        //拿到CGLIB$CALLBACK_0对象的target对象
        Field target = o.getClass().getDeclaredField("target");
        target.setAccessible(true);
        Object t = target.get(o);
        return t;
    }

    public static boolean isJdkProxy(@Nullable Object object) {
        return Proxy.isProxyClass(object.getClass());
    }

    public static final String CGLIB_CLASS_SEPARATOR = "$$";
    public static boolean isCglibProxy(@Nullable Object object) {
        return object.getClass().getName().contains(CGLIB_CLASS_SEPARATOR);
    }
}
